<template>
  <div class="big">
    <div class="loginbox">
      <el-form ref="form" :model="data" :rules="loginFormRules" label-position="right" label-width="auto" show-message>
        <h2>考研资料分享系统</h2>

        <!-- Telephone Input -->
        <el-form-item prop="telephone">
          <el-input v-model="data.telephone" placeholder="手机号/工号" ></el-input>
        </el-form-item>

        <!-- Password Input -->
        <el-form-item prop="password">
          <el-input v-model="data.password" type="password" placeholder="密码" ></el-input>
        </el-form-item>

        <!-- User Type Selection -->
        <el-form-item>
          <el-radio-group v-model="data.utype">
            <el-radio label="0">普通用户</el-radio>
            <el-radio label="1">管理员</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- Login Button -->
        <el-form-item style="margin-left:80px;">
          <el-button type="primary" style="width:200px" @click="onSubmit">登录</el-button>
        </el-form-item>

        <!-- Links for forgot password and register -->
        <el-form-item>
          <el-link type="primary" style="float:left;">忘记密码？</el-link>
          <el-link type="primary" style="float:right;" @click="goRegister">注册</el-link>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useCookies } from '@vueuse/integrations/useCookies';
import axios from 'axios';
import { ElMessage } from 'element-plus';

const router = useRouter();
const { set } = useCookies();
const data = ref({})
// Reactive form data
const form = ref({
  telephone: '',
  password: '',
  utype: '0' // Default to 普通用户
});

// Form validation rules
const loginFormRules = {
  telephone: [
    { required: true, message: '账号不可为空', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '密码不可为空', trigger: 'blur' }
  ]
};

// Submit function
const onSubmit = async () => {
  try {
    const result = await axios.post('/ky/user/login', form.value);
    if (result.data.code === 200) {
      set('uid', result.data.id);
      ElMessage.success(result.data.message);
      const redirectUrl = result.data.utype === 1 ? '/adminLogin' : '/index';
      await router.push(redirectUrl);
    } else {
      ElMessage.error('账号或密码有误!');
    }
  } catch (error) {
    console.error('登录请求出错:', error);
    ElMessage.error('登录请求出错，请检查网络或重试');
  }
};

// Redirection function
const goRegister = () => {
  router.push('/register');
};
</script>

<style scoped>
.loginbox {
  border: 1px solid #DCDFE6;
  background-color: rgb(236, 233, 233);
  width: 350px;
  margin: 180px auto;
  padding: 35px 35px 15px 35px;
  border-radius: 5px;
}
</style>